'''
Playwright支持两种编写模式，一种和Pyppeteer一样的异步模式，一种是和Selenium一样的同步模式。
'''
# 同步模式示例
# from playwright.sync_api import sync_playwright
#
# with sync_playwright() as p:
#     browser = p.chromium.launch(headless=False)
#     context = browser.new_context()
#     page = context.new_page()
#     page.goto('https://www.baidu.com')
#     page.screenshot(path='screenshot=title.png')
#     print(page.title())
#     browser.close()

# 异步模式示例
# import asyncio
# from playwright.async_api import async_playwright
#
# async def main():
#     async with async_playwright() as p:
#         browser = await p.chromium.launch(headless=False)
#         page = await browser.new_page()
#         await page.goto('https://www.baidu.com')
#         await page.screenshot(path='screenshot=title.png')
#         print(await page.title())
#         await browser.close()
# asyncio.run(main())

# 支持移动端浏览器
# from playwright.sync_api import sync_playwright
#
# with sync_playwright() as p:
#     iphone_12_pro_max = p.devices['iPhone 12 Pro Max']
#     browser = p.webkit.launch(headless=False)
#     context = browser.new_context(**iphone_12_pro_max,locale='zh-CN')
#     page = context.new_page()
#     page.goto('https://www.whatismybrowser.com/')
#     page.wait_for_load_state(state='networkidle')
#     page.screenshot(path='browser-iphone.png')
#     browser.close()

'''
常用操作方法
'''
# 事件监听
# from playwright.sync_api import sync_playwright
#
# def on_response(response):
#     if '/api/movie' in response.url and response.status == 200:
#         print(response.json())
#
# with sync_playwright() as p:
#     browser = p.chromium.launch(headless=False)
#     page = browser.new_page()
#     page.on('response', on_response)
#     page.goto('https://spa6.scrape.center/')
#     page.wait_for_load_state('networkidle')
#     browser.close()

# 网络劫持
from playwright.sync_api import sync_playwright
import re

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()

    def cancel_request(route, request):
        route.abort()

    page.route(re.compile(r"(\.png)|(\.jpg)"), cancel_request)
    page.goto("https://spa6.scrape.center/")
    page.wait_for_load_state('networkidle')
    page.screenshot(path='no_picture.png')
    browser.close()